package com.zmx.gateway.filter;

import com.zmx.gateway.properties.MallAuthProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

/**
 * @Description: CSRF(跨站请求伪造)拦截器
 * @ClassName: CSRFFilter
 * @Author zhaomxr
 * @Date 2022-01-18 16:03
 */
@Slf4j
@Component
public class CSRFFilter implements GlobalFilter, Ordered {

    private static final String HTTP = "http://";
    private static final String HTTPS = "https://";
    private static Set<String> refererList;

    @Autowired
    private MallAuthProperties mallAuthProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //request参数
        ServerHttpRequest request = exchange.getRequest();
        //if (shouldFilter(request)) {
        //    //直接拒绝
        //    log.info("当前Referer错误，疑似CSRF攻击，已拒绝访问。");
        //    ServerHttpResponse response = exchange.getResponse();
        //    response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //    DataBuffer bodyDataBuffer = response.bufferFactory().wrap("当前Referer错误，疑似CSRF攻击，已拒绝访问".getBytes());
        //    response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        //    return response.writeWith(Mono.just(bodyDataBuffer));
        //}

        //通过这个过滤器，进入过滤链中的下一个过滤器
        return chain.filter(exchange);
    }

    private boolean shouldFilter(ServerHttpRequest request) {
        String referer = request.getHeaders().getFirst("Referer");
        log.info("referer: {}", referer);
        if (!StringUtils.isEmpty(referer)) {
            if (refererList == null || refererList.size() == 0) {
                refererList = mallAuthProperties.getRefererList();
            }
            if (refererList == null || refererList.size() == 0) {
                return true;
            }

            for (String refererSys : refererList) {
                if (referer.startsWith(HTTP + refererSys) || referer.startsWith(HTTPS + refererSys)) {
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
